#include<bits/stdc++.h>
using namespace std;

int main() {
    //fstream f;
    //fstream f1;
    //f.open("./1.in", ios::in);
    //f1.open("./1.out", ios::out);
    int n;
    cin >> n;
    vector<int> h(n);
    for (int i = 0; i < n; i++) {
        cin >> h[i];
    }

    int ans = 0;
    stack<int> st; 

    for (int i = 0; i < n; i++) {
        while (!st.empty() && h[i] > h[st.top()]) {
            int top = st.top(); 
            st.pop(); 
            if (st.empty()) break; 
            int distance = i - st.top() - 1; 
            int bounded_height = min(h[i], h[st.top()]) - h[top]; 
            ans += distance * bounded_height; 
        }
        st.push(i); 
    }

    cout << ans << endl;
    return 0;
}